package Selection;

import GA.Chromosome;
import GA.Selection;

public class RankingSelection implements Selection{
	/**
 		Each individual in the population is assigned a numerical rank based on fitness,
 		and selection is based on this ranking.
 		
 		Rank selection first ranks the population and then every chromosome receives 
 		fitness from this ranking. The worst will have fitness 1, second worst 2 etc. 
 		and the best will have fitness N (number of chromosomes in population). 
 		
	 **/
	
	private RouletteSelection roulette;		// Roulette to select chromosomes after ranking
	
	public RankingSelection(){
		this.roulette = new RouletteSelection();
	}

	public Chromosome[] selection(Chromosome[] population, int populationSize) {
		Chromosome[] newPopulation = AuxFunctions.PopulationFun.sortPopulation(population);	// Sort population
		
		// Ranking: Sets aptitude from 1 (worst) to N (better)
		for (int i = 0; i < populationSize; i++)
			newPopulation[i].setAptitude(populationSize - i);
		
		AuxFunctions.PopulationFun.setScores(newPopulation);			// Sets scores of population
		newPopulation = roulette.selection(newPopulation, populationSize);		// Selection by roulette
		
		return AuxFunctions.PopulationFun.evaluate(newPopulation);
	}

}
